import { asyncRoutes, constantRoutes } from '@/router'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

/**
 * 导航转成路由
 */
const menuToRoute = (menu) => {
  if (!menu.component) {
    return null
  }
  const route = {
    name: menu.name,
    path: menu.path,
    redirect: menu.redirect,
    hidden: menu.hidden,
    alwaysShow: menu.alwaysShow,
    meta: {
      icon: menu.iconName,
      title: menu.title,
      noCache: menu.noCache,
      breadcrumb: menu.breadcrumb,
      affix: menu.affix,
      activeMenu: menu.activeMenu
    },
    children: []
  }
  route.component = () => Promise.resolve(require(`@/views/${menu.component}`).default)
  return route
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param newRoutes 新路由信息
 */
export function addAsyncRoutes(routes, newRoutes) {
  newRoutes.forEach(route => {
    routes.unshift(menuToRoute(route))
    if (route.children) {
      route.children.forEach(e => {
        routes[0].children.unshift(menuToRoute(e))
        if (e.children) {
          e.children.forEach(item => {
            routes[0].children[0].children.push(menuToRoute(item))
          })
        } else {
          delete routes[0].children[0]
        }
      })
    } else {
      delete routes[0].children
    }
  })
  console.log(routes)
  return routes
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  RESET_ROUTES: (state) => {
    state.addRoutes = []
    state.routes = []
  }
}

const actions = {
  generateRoutes({ commit }, routes) {
    return new Promise(resolve => {
      const accessedRoutes = addAsyncRoutes(asyncRoutes, routes)
      // if (roles.includes('sys-root')) {
      //   accessedRoutes = asyncRoutes || []
      // } else {
      //   accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      // }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  },
  resetRoutes({ commit }) {
    return new Promise(resolve => {
      commit('RESET_ROUTES')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
